﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CustomerController.cs" company="Oliver Kurowski">
//    (c) Oliver Kurowski. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace RegioKistl.Views.Customer
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;

    using RegioKistl.Models;
    using RegioKistl.Models.DataAccess;

    public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            using (var session = Repository.OpenSession())
            {
                var customers = session.Query<Models.Customer>()
                    .Customize(x => x.WaitForNonStaleResults(TimeSpan.FromSeconds(5)))
                    .ToList();

                return View(customers);
            }
        }

        //
        // GET: /Customer/Details/5

        public ActionResult Details(int id = 0)
        {
            using (var session = Repository.OpenSession())
            {
                var customer = session.Load<Models.Customer>(id);

                if (customer == null)
                {
                    return this.HttpNotFound();
                }

                return this.View(customer);
            }
        }

        //
        // GET: /Customer/Create

        public ActionResult Create()
        {
            using (var userContext = new UsersContext())
            {
                var profileInfo = from u in userContext.UserProfiles
                                  select new SelectListItem
                                  {
                                      Selected = false,
                                      Text = u.UserName,
                                      Value = u.UserName
                                  };

                this.ViewBag.AllUserProfiles = profileInfo.ToList();
            }

            return View();
        }

        //
        // POST: /Customer/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Models.Customer customer)
        {
            if (!this.User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index");
            }

            if (this.ModelState.IsValid)
            {
                customer.AccountName = this.User.Identity.Name;

                using (var session = Repository.OpenSession())
                {
                    session.Store(customer);
                    session.SaveChanges();
                }

                return RedirectToAction("Index");
            }

            return this.View(customer);
        }

        //
        // GET: /Customer/Edit/5

        public ActionResult Edit(int id = 0)
        {
            using (var userContext = new UsersContext())
            {
                var profileInfo = from u in userContext.UserProfiles
                                  select new SelectListItem
                                  {
                                      Selected = false,
                                      Text = u.UserName,
                                      Value = u.UserName
                                  };

                this.ViewBag.AllUserProfiles = profileInfo.ToList();
            }

            using (var session = Repository.OpenSession())
            {
                var customer = session.Load<Models.Customer>(id);

                if (customer == null)
                {
                    return this.HttpNotFound();
                }

                return this.View(customer);
            }
        }

        /// <summary>
        /// Calls the edit page for the customer that has the given name as AccountName.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public ActionResult EditByAccount(string name = "")
        {
            if (string.IsNullOrEmpty(name))
            {
                return this.HttpNotFound();
            }

            this.ViewBag.AllUserProfiles = new List<SelectListItem>
                                               {
                                                   new SelectListItem { Text = name, Value = name }
                                               };

            using (var session = Repository.OpenSession())
            {
                var customer = (from c in session.Query<Models.Customer>()
                                where c.AccountName == name
                                select c).FirstOrDefault();

                if (customer == null)
                {
                    return this.HttpNotFound();
                }

                return this.View(customer);
            }
        }

        //
        // POST: /Customer/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Models.Customer customer)
        {
            ActionResult view;

            if (this.SaveChangesFromEdit(customer, out view))
            {
                return view;
            }

            return this.RedirectToAction("Index");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditByAccount(Models.Customer customer)
        {
            ActionResult view;

            if (this.SaveChangesFromEdit(customer, out view))
            {
                return view;
            }

            return this.RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// Saves the changes from edit.
        /// </summary>
        /// <param name="customer">The customer.</param>
        /// <param name="view">The view.</param>
        /// <returns></returns>
        private bool SaveChangesFromEdit(Customer customer, out ActionResult view)
        {
            view = null;

            if (!this.ModelState.IsValid)
            {
                view = this.View(customer);
                return true;
            }

            using (var session = Repository.OpenSession())
            {
                session.Store(customer);
                session.SaveChanges();
            }

            return false;
        }

        //
        // GET: /Customer/Delete/5

        //public ActionResult Delete(int id)
        //{
        //    return View();
        //}

        //
        // POST: /Customer/Delete/5

        //[HttpPost]
        //public ActionResult Delete(int id, FormCollection collection)
        //{
        //    try
        //    {
        //        // TODO: Add delete logic here

        //        return RedirectToAction("Index");
        //    }
        //    catch
        //    {
        //        return View();
        //    }
        //}
    }
}
